package com.zhm.demo.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;

@Slf4j
public class TechFineMqttClient {

    private static MqttClient sampleClient;

    public static void main(String[] args) throws Exception {
        connect();
        while (true) ;
    }

    public static void connect() throws MqttException, InterruptedException {
        //接入物联网平台的域名。
        String broker = "tcp://172.24.73.21:10086";
        String clientId = "124";
        String username = "admin";
        String password = "382346819(){}|Pl";

// Paho MQTT客户端。
        sampleClient = new MqttClient(broker, clientId);

// Paho MQTT连接参数。
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        connOpts.setKeepAliveInterval(180);
        connOpts.setUserName(username);
        connOpts.setPassword(password.toCharArray());
        sampleClient.connect(connOpts);
        System.out.println("Broker: " + broker + " Connected");


        String uplinkTopic = "/sys/device/runtimedata/techFineInverter/330022320240308/uplink";
        String downlinkTopic = "/sys/device/devicestatus/techFineInverter/330022320240308/downlink";
        sampleClient.subscribe(uplinkTopic, new MqttPostPropertyMessageListener());
        sampleClient.subscribe(downlinkTopic, new MqttPostPropertyMessageListener());

        String str = "(223.2 50.0 000.0 00.0 0000 " + "0340" + " 000 010 00.00 000 000 0017 00.0 000.0 00.00 00000 00000000 00 00 00000 0000 00.0 0303'";
        while (true) {
            Thread.sleep(5000);
            send("/sys/device/runtimedata/techFineInverter/330022320240308/uplink", str.getBytes());
        }
    }

    public static void send(String topic, byte[] content) throws MqttException {
        // Paho MQTT发布消息。
//        String topic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
//        String content = "{\"id\":\"1\",\"version\":\"1.0\",\"params\":{\"LightSwitch\":1}}";
        MqttMessage message = new MqttMessage(content);
        message.setQos(0);
        sampleClient.publish(topic, message);
    }

    public static class MqttPostPropertyMessageListener implements IMqttMessageListener {
        @Override
        public void messageArrived(String var1, MqttMessage var2) throws Exception {
            log.info("reply topic  : {}", var1);
            log.info("reply payload: {}", var2);
        }
    }

}
